package com.ucode.wap.hrm.controller;

import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.ucode.hrm.service.HrmCustomerCompanyService;
import com.ucode.hrm.service.HrmCustomerProjectService;
import com.ucode.hrm.service.HrmEmployeeService;
import com.ucode.model.hrm.HrmCustomerCompany;
import com.ucode.model.hrm.HrmCustomerProject;
import com.ucode.model.hrm.HrmEmployee;
import com.ucode.model.hrm.convert.HrmEmployeeConvert;
import com.ucode.model.hrm.enums.HrmEmploymentTypeEnum;
import com.ucode.model.hrm.enums.HrmSysResultCodeEnum;
import com.ucode.model.hrm.form.HrmEmployeeBindForm;
import com.ucode.model.hrm.form.HrmEmployeeEditForm;
import com.ucode.model.hrm.vo.HrmEmployeeVO;
import com.ucode.tool.annotation.NeedLogin;
import com.ucode.tool.base.ResponseResult;
import com.ucode.tool.base.enums.SexEnum;
import com.ucode.tool.exception.UcodeServiceException;
import com.ucode.tool.util.IdentifyUtils;
import com.ucode.wap.base.core.CurrentLoginUserHandler;
import com.ucode.wap.hrm.service.ApiHrmEmployeeService;
import com.ucode.wap.hrm.service.ApiHrmExcelHandleService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;

@Tag(name = "移动端 - 人力资源系统 - 员工")
@RestController
@RequestMapping("/hrm/employee")
@Validated
public class ApiHrmEmployeeController {

    private static Log log = LogFactory.get();

    @Resource
    private CurrentLoginUserHandler currentLoginUserHandler;
    @Resource
    private HrmCustomerProjectService customerProjectService;
    @Resource
    private HrmCustomerCompanyService customerCompanyService;
    @Resource
    private HrmEmployeeService employeeService;
    @Resource
    private ApiHrmEmployeeService apiHrmEmployeeService;

    @Resource
    private ApiHrmExcelHandleService apiHrmExcelHandleService;

    @NeedLogin(validate = true)
    @GetMapping("/status")
    @Operation(summary = "验证员工状态")
    public ResponseResult<Boolean> verifyEmployeeStatus(){
        HrmEmployee bean = employeeService.selectBindStatusInfo(currentLoginUserHandler.getCurrentUserId());
        return ResponseResult.success(ObjUtil.isNotNull(bean) && !bean.getDeltag() && !ObjUtil.equals(bean.getEmploymentType(), HrmEmploymentTypeEnum.LEFT.getCode()) && !ObjUtil.equals(bean.getEmploymentType(), HrmEmploymentTypeEnum.APPLY.getCode()));
    }

    @NeedLogin(validate = true)
    @PostMapping("/bind")
    @Operation(summary = "员工绑定")
    public ResponseResult<HrmEmployeeVO> bind(@Valid @RequestBody HrmEmployeeBindForm form){
        HrmEmployee bean = employeeService.selectStatusByIdentity(form.getRealName(),  form.getIdCardNumber());
        apiHrmEmployeeService.verifyEmployeeStatus(bean);
        int i = employeeService.bind(bean.getId(), currentLoginUserHandler.getCurrentUserId());
        if(i == 0){
            throw new UcodeServiceException(HrmSysResultCodeEnum.EMPLOYEE_BIND_OTHER_ERROR);
        }
        return ResponseResult.success(getById(bean.getId()));
    }

    @NeedLogin(validate = true)
    @GetMapping("/current/info")
    @Operation(summary = "当前员工信息")
    public ResponseResult<HrmEmployeeVO> getCurrentInfo(){
        HrmEmployee bean = employeeService.selectBindStatusInfo(currentLoginUserHandler.getCurrentUserId());
        if(ObjUtil.isNotNull(bean)){
            return ResponseResult.success(getById(bean.getId()));
        }else {
            return ResponseResult.success();
        }
    }

    /**
     * 主键查询员工信息
     * @param id
     * @return
     */
    private HrmEmployeeVO getById(Long id){
        HrmEmployee bean = employeeService.validate(id);
        HrmEmployeeVO vo = HrmEmployeeConvert.INSTANCE.convert(bean);
        if(ObjUtil.isNotNull(vo.getCompanyId())){
            HrmCustomerCompany customerCompany = customerCompanyService.selectByPrimaryKey(bean.getCompanyId());
            if(customerCompany != null)
                vo.setCompanyName(customerCompany.getCompanyName());
        }

        if(ObjUtil.isNotNull(vo.getProjectId())){
            HrmCustomerProject project = customerProjectService.selectByPrimaryKey(bean.getProjectId());
            if(project != null)
                vo.setProjectName(project.getProjectName());
        }

        return vo;
    }


    @NeedLogin(validate = true)
    @PostMapping("/update")
    @Operation(summary = "修改信息")
    public ResponseResult<Boolean> update(@Valid @RequestBody HrmEmployeeEditForm form) {
        HrmEmployee bean = HrmEmployeeConvert.INSTANCE.convert(form);
        if(StrUtil.isNotBlank(bean.getIdCardNumber())){
            //从身份证中获取出生日期
            bean.setBirthDate(IdcardUtil.getBirthDate(bean.getIdCardNumber()).toLocalDateTime().toLocalDate());
            //根据身份证号码获取籍贯
            bean.setRegisteredResidence(IdcardUtil.getProvinceByIdCard(bean.getIdCardNumber()));
            //根据身份证号码获取性别
            bean.setGender(IdcardUtil.getGenderByIdCard(bean.getIdCardNumber()) == 1 ? SexEnum.MALE.getCode() : SexEnum.FEMALE.getCode());
        }

        HrmEmployee dbBean = employeeService.selectBindStatusInfo(currentLoginUserHandler.getCurrentUserId());
        if(ObjUtil.isNotNull(dbBean)){
            bean.setId(dbBean.getId());
            employeeService.update(bean);
        }else {

            //先根据身份证查询员工
            HrmEmployee dbBeanByIdCard = employeeService.getByIdCardNumber(bean.getIdCardNumber());
            if(ObjUtil.isNotNull(dbBeanByIdCard)){
                bean.setId(dbBeanByIdCard.getId());
                bean.setMemberId(currentLoginUserHandler.getCurrentUserId());
                employeeService.update(bean);
            }else{
                bean.setId(IdentifyUtils.getDefaultSnowflakeId());
                bean.setEmploymentType(HrmEmploymentTypeEnum.APPLY.getCode());
                bean.setMemberId(currentLoginUserHandler.getCurrentUserId());
                employeeService.insert(bean);
            }
        }
        return ResponseResult.success(true);
    }

    // POST请求处理方法，接收上传的Excel文件
    //@PostMapping("/parse") // 映射到/api/excel/parse
    //public ResponseResult<Boolean> parseExcel(@RequestParam("file") MultipartFile file) throws IOException {
    //
    //    new Thread(() -> {
    //        try {
    //            apiHrmExcelHandleService.importEmployeesData(file);
    //        } catch (Exception e) {
    //            log.error("导入员工异常了...",e);
    //        }
    //    }).start();
    //    return ResponseResult.success();
    //}

}
